package com.cordova.test.imageselect.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.cordova.test.imageselect.R
import com.cordova.test.imageselect.module.ImageFolder

class PopupAdapter(context: Context) : RecyclerView.Adapter<PopupAdapter.PopupViewHolder>() {

    private var context: Context = context
    private var mFolders: ArrayList<ImageFolder>? = null
    fun setFolderList(folders: ArrayList<ImageFolder>?) {
        this.mFolders = folders
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(p0: ViewGroup, p1: Int): PopupViewHolder {
        val itemView: View = LayoutInflater.from(context).inflate(R.layout.popup_item_layout, p0, false)
        return PopupViewHolder(itemView)
    }

    override fun getItemCount(): Int {
        return if (mFolders == null) 0 else mFolders!!.size
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(p0: PopupViewHolder, p1: Int) {
        Glide.with(context).load(mFolders!![p1].cover?.path).error(R.mipmap.v).into(p0.imgCover)
        p0.tvTitle.text = mFolders!![p1].name
        var folderTotal: String = context.resources.getString(R.string.total_img)
        folderTotal = String.format(folderTotal, mFolders!![p1].images?.size)
        p0.tvDes.text = folderTotal
        p0.itemView.tag = p1

        p0.itemView.setOnClickListener {
            mItemClickListener.onItemClickListener(p0, p1)
            if (p0.imgCheck.visibility ==View.GONE){
                p0.imgCheck.visibility = View.VISIBLE
            }else{
                p0.imgCheck.visibility = View.GONE
            }
        }
    }

    private lateinit var mItemClickListener: OnFolderItemClickListener
    fun setFolderItemClickListener(itemClickListener: OnFolderItemClickListener) {
        this.mItemClickListener = itemClickListener
    }

    interface OnFolderItemClickListener {
        fun onItemClickListener(viewHolder: PopupViewHolder, position: Int)
    }


    class PopupViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var imgCover: ImageView = itemView.findViewById(R.id.img_cover) as ImageView
        var tvTitle: TextView = itemView.findViewById(R.id.tv_title) as TextView
        var tvDes: TextView = itemView.findViewById(R.id.tv_des) as TextView
        val imgCheck: ImageView = itemView.findViewById(R.id.img_checked) as ImageView
    }
}